package com.ndp.fb.walle.config;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.ndp.fb.constant.Constant;
import com.ndp.fb.exception.CheckedException;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.NestedServletException;

import javax.servlet.*;
import java.io.IOException;

/**
 * Created by hunk.qin on 2016/3/18.
 */
public class RestExceptionFilter implements Filter {

    Logger logger = LoggerFactory.getLogger(RestExceptionFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try{
            chain.doFilter(request, response);
        }
        catch (Exception e){
            logger.error(e.getMessage(),e);
            RestModel restModel=new RestModel(false,e.getMessage(),"", "","fail");
            if(e instanceof NestedServletException){
                Throwable cause =  e.getCause();
                restModel.setErrorMsg(e.getCause().getMessage());
                if (cause instanceof CheckedException){
                    CheckedException che = (CheckedException)cause;
                    if (!StringUtil.isEmpty(che.getErrorCode())){
                        String errorMsg = ResponseUtils.getMsgByKey(che.getErrorCode());
                        restModel.setErrorMsg(errorMsg);
                    }

                    restModel.setErrorCode(che.getErrorCode());
                }
            }

            response.setContentType("application/json");
            response.getOutputStream().write(JSON.toJSONString(restModel).getBytes("Unicode"));
        }
    }

    @Override
    public void destroy() {

    }
}
